<template>
  <el-select
    v-model="Model"
    v-bind="$attrs"
    v-on="$listeners"
    style="width: -webkit-fill-available"
    multiple
    collapse-tags
    @remove-tag="removeTag"
    @visible-change="visibleChange"
    :placeholder="placeholder"
  >
    <template #empty>
      <div style="width: 750px; margin: 10px">
        <EvForm
          v-bind="$attrs"
          ref="dataSourceForm"
          :itemStyle="{ marginRight: '2%', marginBottom: '10px', width: '95%' }"
          :autoWidth="false"
          @autoEmit="handleQuery"
        >
        </EvForm>
        <EvTable
          :options="{
            data: data,
            columns,
            height: '320px',
            toolbarConfig: {
              custom: false,
              slots: {
                buttons: 'toolbar_buttons',
              },
            },
            checkboxConfig: {
              checkMethod: checkMethod,
            },
          }"
          :tablePage="page"
          @changeEvent="handleModelChange"
          @handlePageChange="handlePageChange"
          ref="EvTable"
        >
        </EvTable>
      </div>
    </template>
  </el-select>
</template>

<script>
export default {
  props: {
    value: {
      type: [String, Number, Array],
    },
    columns: {
      type: Array,
      default: () => [],
    },
    fieldValue: String,
    fieldLabel: String,
    fieldLock: {
      type: Array,
      default: () => [],
    },
    microservices: {
      type: String,
      default: "",
    },
    resource: {
      type: String,
      default: "",
    },
    placeholder: {
      type: String,
      default: "",
    },
  },
  async mounted() {
    await this.handleQuery();
    this.Model = this.selectedModel.map((valueItem) =>
      this.getValueFromObject(
        this.data?.filter((item) => this.getValueFromObject(item, this.fieldValue) === valueItem)[0],
        this.fieldLabel
      )
    );

    this.$emit("input", this.selectedModel);
  },
  beforeDestroy() {
    this.dataCache = [];
    this.data = [];
  },
  data() {
    return {
      selectedModel: this.value,
      selectedValue: null,
      page: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
      },
      searchQueries: {},
      Model: "",
      data: [],
      setCheckboxRow: {},
      dataCache: [],
    };
  },
  watch: {
    selectedModel(newVal) {
      this.$emit("input", newVal);
    },
    value() {
      this.setCheckbox();
    },
  },
  methods: {
    checkMethod({ row }) {
      for (let i = 0; i < this.fieldLock.length; i++) {
        if (!this.getValueFromObject(row, this.fieldLock[i])) {
          return false;
        }
      }
      return true;
    },
    visibleChange(visible) {
      if (visible) {
        this.$refs.dataSourceForm.resetFields();
        this.handleQuery();
      }
    },
    removeTag(tag) {
      const tagObj = this.dataCache.find((item) => this.getValueFromObject(item, this.fieldLabel) === tag);
      const tagValue = this.getValueFromObject(tagObj, this.fieldValue);
      const index = this.selectedModel.findIndex((item) => {
        return item === tagValue;
      });

      if (index !== -1) {
        this.selectedModel.splice(index, 1);
      }

      this.$refs.EvTable.setCheckboxRow(tagObj, false);
    },
    async handleQuery() {
      return new Promise((resolve) => {
        this.page.currentPage = 1;
        this.searchQueries = { AND: [] };
        this.$attrs.dataSourceFormOptions.dataSourceFormItems.forEach((item) => {
          const { model, type, dateType, notUse } = item; // 添加 dateType
          const value = this.getValueByModel(model);

          if (value !== null && value !== undefined && value !== "") {
            let query;

            if (notUse) {
              return;
            }

            switch (type) {
              case "input":
                query = [model, "LIKE", `%${value}%`];
                break;
              case "select":
                query = [model, "=", value];
                break;
              case "date":
                if (dateType === "daterange") {
                  query = [model, "BETWEEN '%s' AND '%s'", value]; // 修改为 BETWEEN 操作符
                } else {
                  query = [model, ">", value];
                }
                break;
              // 添加其他类型的处理逻辑
            }
            this.searchQueries.AND.push(query);
          }
        });

        // 添加公共条件
        this.searchQueries.AND.push(["isDelete", "=", 0]);
        this.page.currentPage = 1;

        this.loadData().then(() => {
          resolve();
        });
      });
    },
    getValueByModel(model) {
      const keys = model.split(".");
      let value = this.$attrs.dataSourceFormOptions.dataSourceForm;

      keys.forEach((key) => {
        // 检查是否为对象类型
        if (typeof value === "object" && value !== null) {
          value = value[key];
        } else {
          value = null;
        }
      });

      return value;
    },
    getValueFromObject(obj, path) {
      const keys = path.split(".");
      let value = obj;

      for (const key of keys) {
        if (value && typeof value === "object") {
          value = value[key];
        } else {
          value = undefined;
          break;
        }
      }

      return value;
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage;
      this.page.pageSize = pageSize;
      this.loadData();
    },
    setCheckbox() {
      const checkboxes = this.selectedModel.map((valueItem) => {
        return this.data.find((item) => this.getValueFromObject(item, this.fieldValue) === valueItem);
      });
      this.$refs.EvTable.setCheckboxRow(checkboxes, true);
      this.$refs.EvTable.selectRecords = checkboxes;
    },
    loadData() {
      return new Promise((resolve) => {
        this.$server()
          .query(
            this.microservices,
            this.resource,
            this.searchQueries,
            null,
            { current: this.page.currentPage, size: this.page.pageSize },
            true
          )
          .then((response) => {
            this.page.total = response.total;
            this.data = response.list;
            this.dataCache = [...new Set([...this.dataCache, ...this.data])];
            this.$emit("optionSet", this.dataCache);
            this.setCheckbox();
            resolve();
          })
          .catch((response) => {
            this.$message.error(response.data.message);
          });
      });
    },
    handleModelChange(data) {
      if (!data || data.length === 0) {
        this.selectedModel = [];
        this.selectedValue = [];
        this.Model = "";
        this.$emit("input", this.selectedValue);
        this.$emit("change", this.selectedValue);
        this.$emit("selectData", data);
        return;
      }

      const fieldLabelValues = data?.map((item) => this.getValueFromObject(item, this.fieldLabel));
      const fieldValueValues = data?.map((item) => this.getValueFromObject(item, this.fieldValue));

      if (fieldLabelValues !== undefined) {
        this.Model = [...new Set([...this.Model, ...fieldLabelValues])];
      }

      if (fieldValueValues) {
        let uniqueValues;
        if (this.selectedModel.length >= 1) {
          uniqueValues = new Set([...this.selectedModel, ...fieldValueValues]);
        } else {
          uniqueValues = new Set([...fieldValueValues]);
        }

        // 转换回数组
        this.selectedModel = [...uniqueValues];
        this.selectedValue = [...uniqueValues];
      }

      this.$emit("input", this.selectedValue);
      this.$emit("change", this.selectedValue);
      this.$emit("selectData", data);
    },
  },
};
</script>
